<template>
    <div class="layout-item" :class="{
        'layout-item_active': isActive
    }" :style="layoutItemStyle" @click.stop="handelClick($event)">
        <template  v-if="property.children && property.children.length">
            <GridView :layout="property.children" :direction="property.direction" :wrap="property.wrap" :col="property.col">
                <template #default="{ grid }">
                    <slot :grid="grid"></slot>
                </template>
            </GridView>
        </template>
        <template v-else>
            <slot :grid="property">{{property.name}}</slot>
        </template>
    </div>
</template>

<script>
import { DirectionEnum } from './util/emnu'
export default {
    name: 'GridViewItem',
    props: {
        // 数据
        property: {
            type: Object,
            require: true
        },
        // 唯一标识
        nodeKey: {
            type: String,
            default: 'id'
        },
        // flex方向
        direction: {
            type: String,
            default: 'row',
            validator: (value) => DirectionEnum.indexOf(value) !== -1,
        },
        // 换行时每行个数
        col: Number
    },
    inject: ['VoGridView'],
    data() {
        return {}
    },
    computed: {
        // 当前是否被选中
        isActive() {
            const { property, nodeKey } = this
            const { currentItem } = this.VoGridView
            return currentItem ? currentItem[nodeKey] === property[nodeKey] : false
        },
        // 样式
        layoutItemStyle() {
            const { col, direction } = this
            const stl = {}
            if (!isNaN(col) && typeof col === 'number' && col > 0) {
                if (direction === 'column' || direction === 'column-reverse') {
                    stl.minHeight = `${100 / col}%`
                    stl.maxHeight = `${100 / col}%`
                } else {
                    stl.minWidth = `${100 / col}%`
                    stl.maxWidth = `${100 / col}%`
                }
            }
            return stl
        }
    },
    created() {
        // 依赖收集
        const { bus } = this.VoGridView
        if (bus) {
            bus.$emit('collect-add', this)
        }
    },
    beforeDestroy() {
        // 依赖移除
        const { bus } = this.VoGridView
        if (bus) {
            bus.$emit('collect-remove', this)
        }
    },
    methods: {
        // 点击事件
        handelClick(el) {
            const { bus } = this.VoGridView
            if (bus) {
                bus.$emit('on-change', this.property, el)
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.layout-item{
    display: inline-block;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    flex: 1;
    transition: all 0.2s;
    &.layout-item_active{
        border-color: #039E35;
    }
    &:hover{
        border-color: #F56C6C;
    }
}
</style>
